package com.admin.education.services.Implements;

import com.admin.education.common.exceptions.BadRequestException;
import com.admin.education.config.WechatConfig;
import com.admin.education.dataTransferObject.wx.WXTransfer;
import com.admin.education.services.Interfaces.IWXService;
import com.alibaba.fastjson.JSONObject;
import org.javalite.http.Get;
import org.javalite.http.Http;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotBlank;

@Service
@Validated
public class WXService implements IWXService {
    @Autowired
    private WechatConfig wechatConfig;
    @Override
    public WXTransfer Authenticate(@NotBlank String code) throws Exception {
        String url = String.format("https://api.weixin.qq.com/sns/jscode2session?grant_type=%s&appid=%s&js_code=%s&secret=%s",
                wechatConfig.getGrantType(), wechatConfig.getAppId(), code, wechatConfig.getSecret()).replace("\"","");
        Get get = Http.get(url);
        int responseCode = get.responseCode();

        switch (responseCode) {
            case 200:
                String json = get.text();
                JSONObject jsonObject = JSONObject.parseObject(json) ;
                if(jsonObject.containsKey("errcode")){
                    throw new BadRequestException(jsonObject.get("errmsg").toString());
                }
                return  JSONObject.parseObject(json,WXTransfer.class);
            default:
                throw new BadRequestException("微信认证失败");
        }
    }
}
